

#include <sudoku.h>

#include <stdlib.h>

extern sudoku *solution;

int sdk_solved(sudoku *sdk){

  int i = 0;
  int j;
  for ( ; i < SDK_WIDTH; i++){
    j = 0;
    for ( ; j < SDK_WIDTH; j++){
      if (SDK_GET_SQUARE_VAL(sdk, i, j) == 0) return 0;
    }
  }

  sdk->solved = 1;
  return 1;

}

sudoku *sdk_solve(sudoku *sdk){

  sudoku *possible_sol = _sdk_solve(sdk);
  
  if (possible_sol) return possible_sol;
  
  /* Else... */
  /* Do a recursive depth first brute force search for the solution */
  
  solution = NULL;
  _sdk_rec_solve(sdk);
  return solution; // Automatically filled in by the recursive solver.

}

/**
 * Solves all "easy" squares. This may or may not fully solve the sudoku.
 */
sudoku *_sdk_solve(sudoku *sdk){

  sdk_generate_lists(sdk);
  while (sdk_set_square_vals(sdk))
    sdk_generate_lists(sdk);

  if (sdk_solved(sdk)) return sdk;
  else return NULL;

}

int sdk_solvable(sudoku *sdk){

  int i = 0, j;
  for ( ; i < SDK_WIDTH; i++){
    for ( j = 0; j < SDK_WIDTH; j++){
      if (sdk_llist_size(SDK_GET_SQUARE(sdk, i, j).pos) == 0) return 0;
    }
  }

  return 1;

}
